package com.weiweiqin.controller.home;

import com.weiweiqin.model.Customer;
import com.weiweiqin.model.Goods;
import com.weiweiqin.model.Prize;
import com.weiweiqin.service.GoodsService;
import com.weiweiqin.service.PrizeService;
import com.weiweiqin.vo.common.Page;
import com.weiweiqin.vo.common.PrizeVO;
import com.weiweiqin.vo.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("front/prize")
public class FPrizeController {

	private static final Logger logger = LoggerFactory.getLogger(FPrizeController.class);

	@Autowired
	private PrizeService prizeService;

	@Autowired
	private GoodsService goodsService;

	/**
	 *
	 * @return
	 */
	@RequestMapping(value = "/list.do", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String list(int currPage,Integer status,HttpSession session) {
		logger.info("Enter method home...");
		Customer customer = (Customer) session.getAttribute("customer");
		Result result = new Result();
		Page page = new Page();
		page.setPageSize(20);
		page.setCurrPage(currPage);
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("customerId", customer.getId());
		if(null != status) {
			conditions.put("status", status);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<Prize> list = null;
		List<PrizeVO> voList = new ArrayList<PrizeVO>();
		int totalCount;
		try {
			list = prizeService.pageList(page, conditions);
			if(null != list && !list.isEmpty()){
				for (Prize prize : list) {
					PrizeVO vo = new PrizeVO();
					vo.setPrize(prize);
					String format = sdf.format(prize.getCreateTime());
					vo.setCreateTime(format);
					Goods goods = goodsService.get(prize.getGoodsId());
					vo.setGoods(goods);
					voList.add(vo);
				}
			}
			totalCount = prizeService.totalCount(conditions);
		} catch (Exception e) {
			logger.error("数据库异常", e);
			result.setErrorMsg("数据库异常");
			result.setResult(false);
			return result.toJson();
		}
		page.setTotalCount(totalCount);
		Map<String, Object> mp = new HashMap<String, Object>();
		mp.put("totalPage", page.getTotalPage());
		mp.put("totalCount", page.getTotalCount());
		mp.put("list", voList);
		result.setObj(mp);
		result.setResult(true);
		return result.toJson();
	}

}
